// 获取电影截图的有效内容矩形区域
function getCroppedRect(imageData) {
  const width = imageData.width;
  const height = imageData.height;
  const data = imageData.data;

  console.log(width, height)

  let top = 0;
  let bottom = height - 1;
  const middleY = Math.floor(height / 2);

  // 从中间向上检查黑边上边界
  for (let y = middleY; y >= 0; y--) {
    if (isRowEmpty(data, width, y)) {
      top = y;
      break;
    }
  }

  // 从中间向下检查黑边下边界
  for (let y = middleY; y < height; y++) {
    if (isRowEmpty(data, width, y)) {
      bottom = y;
      break;
    }
  }

  // 从左到右逐列判断颜色值
  let left = 0;
  let right = width - 1;

  for (let x = 0; x < width; x++) {
    if (!isColumnEmpty(data, width, height, x)) {
      left = x;
      break;
    }
  }

  // 从右到左逐列判断颜色值
  for (let x = width - 1; x >= 0; x--) {
    if (!isColumnEmpty(data, width, height, x)) {
      right = x;
      break;
    }
  }

  // 返回有效内容矩形区域的坐标
  return { top, bottom, left, right };
}

// 判断一行是否为空（颜色值一致）
function isRowEmpty(data, width, y) {
  const startIdx = y * width * 4;
  const endIdx = (y + 1) * width * 4;
  const rowColor = getAverageColor(data, startIdx, endIdx);
  console.log("rowColor", rowColor)
  let sameColor = 0;
  let diffColor = 0;
  for (let i = startIdx + 4; i < endIdx; i += 4) {
    const pixelColor = getPixelColor(data, i);
    // console.log("pixelColor", pixelColor, rowColor)
    if (!colorsAreEqual(rowColor, pixelColor)) {
      diffColor++;
    }
    else{
      sameColor++;
    }
  }
  return (sameColor / (sameColor + diffColor)) > 0.9
}

// 判断一列是否为空（颜色值一致）
function isColumnEmpty(data, width, height, x) {
  const startIdx = x * 4;
  const endIdx = width * height * 4;
  const columnColor = getAverageColor(data, startIdx, endIdx, width);
  for (let i = startIdx + width * 4; i < endIdx; i += width * 4) {
    const pixelColor = getPixelColor(data, i);
    if (!colorsAreEqual(columnColor, pixelColor)) {
      return false;
    }
  }
  return true;
}

// 获取像素点的颜色值
function getPixelColor(data, index) {
  const red = data[index];
  const green = data[index + 1];
  const blue = data[index + 2];
  const alpha = data[index + 3];
  return { red, green, blue, alpha };
}

// 获取指定范围内像素颜色的平均值
function getAverageColor(data, startIdx, endIdx, step = 1) {
  let sumRed = 0;
  let sumGreen = 0;
  let sumBlue = 0;
  let sumAlpha = 0;
  let count = 0;

  for (let i = startIdx; i < endIdx; i += step * 4) {
    sumRed += data[i];
    sumGreen += data[i + 1];
    sumBlue += data[i + 2];
    sumAlpha += data[i + 3];
    count++;
  }

  const avgRed = Math.round(sumRed / count);
  const avgGreen = Math.round(sumGreen / count);
  const avgBlue = Math.round(sumBlue / count);
  const avgAlpha = Math.round(sumAlpha / count);

  return { red: avgRed, green: avgGreen, blue: avgBlue, alpha: avgAlpha };
}

// 判断两个颜色值是否相等
function colorsAreEqual(color1, color2, tolerance = 5) {
  return (
    Math.abs(color1.red - color2.red) <= tolerance &&
    Math.abs(color1.green - color2.green) <= tolerance &&
    Math.abs(color1.blue - color2.blue) <= tolerance &&
    Math.abs(color1.alpha - color2.alpha) <= tolerance
  );
}

function processImage(imageUrl) {
  const sourceImage = new Image();
  sourceImage.crossOrigin = "Anonymous";
  sourceImage.onload = function() {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');

    // 将原图绘制到canvas上
    canvas.width = sourceImage.width;
    canvas.height = sourceImage.height;
    context.drawImage(sourceImage, 0, 0);

    // 获取图片数据
    const imageData = context.getImageData(0, 0, sourceImage.width, sourceImage.height);

    // 获取有效内容矩形区域
    const croppedRect = getCroppedRect(imageData);

    // 打印裁剪区域，确保正确获取到裁剪区域
    console.log(croppedRect);

    // 创建裁剪后的canvas
    const croppedCanvas = document.createElement('canvas');
    const croppedContext = croppedCanvas.getContext('2d');

    // 设置裁剪后的canvas尺寸
    const croppedWidth = croppedRect.right - croppedRect.left + 1;
    const croppedHeight = croppedRect.bottom - croppedRect.top + 1;
    croppedCanvas.width = croppedWidth;
    croppedCanvas.height = croppedHeight;

    // 在裁剪后的canvas上绘制裁剪区域
    croppedContext.drawImage(
      sourceImage,
      croppedRect.left,
      croppedRect.top,
      croppedWidth,
      croppedHeight,
      0,
      0,
      croppedWidth,
      croppedHeight
    );

    // 创建原图和裁剪结果的图像元素
    const originalImageElement = document.createElement('img');
    originalImageElement.src = imageUrl;
    const croppedImageElement = document.createElement('img');
    croppedImageElement.src = croppedCanvas.toDataURL();

    // 将图像元素添加到body中显示
    document.body.appendChild(originalImageElement);
    document.body.appendChild(croppedImageElement);
  };

  sourceImage.onerror = function() {
    console.error('Error loading image');
  };

  sourceImage.src = imageUrl;
}

for(let i = 1; i <= 4; i++){

  processImage(`./test/${i}.jpg`);
}